package com.vma.user.service;



import com.jfinal.plugin.activerecord.Db;
import com.vma.shoes.bizModel.model.Address;

import java.util.Date;
import java.util.List;

/**
 * Created by chenzui on 2017/4/12.
 */
public class AddressService {
    public static void add(Integer userId,String phone,String name,String location,String desc,String province,String city,String area,String defaultStr){
        if(defaultStr.equals("1")){
            Db.update("UPDATE address a SET a.`default` = '0' WHERE user_id =  ?",userId);
        }

        new Address().setCreateTime(new Date()).setStatus("1").setDetail(desc)
                .setLocation(province+city+area).setPhone(phone)
                .setReciverName(name).setUserId(userId)
                .setProvince(province).setCity(city).setArea(area).setDefault(defaultStr)
                .save();


    }

    public static List<Address> qryAddressList(Integer userId){
        List<Address> addresses = Address.dao.find("select * from address where user_id = ? and status = 1",userId);
        return addresses;
    }

    public static void update(int id,String location,String desc,String phone,String name,String province,String city,String area,String defaultStr){
        Address address = Address.dao.findById(id);
        if(location!=null && !"".equals(location)){
            address.setLocation(location);
        }
        if(desc!=null && !"".equals(desc)){
            address.setDetail(desc);
        }
        if(phone != null && !"".equals(phone)){
            address.setPhone(phone);
        }
        if(name != null && !"".equals(name)){
            address.setReciverName(name);
        }
        if(province != null && !"".equals(province)){
            address.setProvince(province);
        }
        if(city != null && !"".equals(city)){
            address.setCity(city);
        }
        if(area != null && !"".equals(area)){
            address.setArea(area);
        }
        if(defaultStr != null && !"".equals(defaultStr)){
            address.setDefault(defaultStr);
            List<Address> addresses = Address.dao.find("SELECT * FROM address WHERE user_id = ? AND status = 1 AND `default` = 1" +
                    " AND id NOT IN (?)",address.getUserId(),id );
            if(addresses != null && addresses.size() > 0){
                for (Address a:addresses) {
                    a.setDefault("0").update();
                }
            }
        }
        address.update();
    }

    public static void delete(int id){
        Address.dao.findById(id).setStatus("0").update();
    }


    public static Address getAddressById(Integer addressId){
        Address address = Address.dao.findById(addressId);
        return address;
    }

}
